﻿/*可扩展组件的管理 
 * 如果配置不支持多线程，则每次都构造新的实例出去；否则为每一个ID维护同一个实例
 * Created By WangZg
 */
using System;
using System.Collections.Generic;
using System.Text;

using Octopus.Logging.Commons;
using Octopus.Logging.Configuration;

namespace Octopus.Logging.ExtendibleSupport
{
    internal class ComponentPool<T> where T : class
    {
        private object locker = new object();
        private Dictionary<string, T> objects = new Dictionary<string, T>(0);
        public delegate void InitComponent(T component, string param);


        public ComponentPool() { }

        private T CreateCompontent(string typeString, string param, InitComponent initFunction)
        {
            object o = TypeLoader.CreateInstance(typeString);
            if (o is T)
            {
                if (initFunction != null) { initFunction(o as T, param); }
            }
            else
            {
                throw new LogException(LogException.ImplInterfaceNoyet);
            }
            return o as T;
        }

        private Dictionary<int, string> ee = new Dictionary<int, string>();
        public T GetCompontent(ComponentEntily fConfig, string subKey, InitComponent initFunction = null)
        {
             string typeString = fConfig.Type;
            if (!fConfig.SupportMultipleThreading)
            {
                return CreateCompontent(typeString,subKey,initFunction) ;
            }

            string key = fConfig.ID + subKey;
            if (objects.ContainsKey(key))
            {
                return objects[key];
            }
            else
            {
                lock (objects)
                {
                    if (!objects.ContainsKey(key))
                    {
                        objects.Add(key, CreateCompontent(typeString, subKey, initFunction));
                    }

                    return objects[key];
                }
            }
        }
    }
}
